<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
        <title>购物车</title>
        <script src="./js/goods.js"></script>
        <script type="text/javascript" src="./js/vue.js"></script>
        <link href="./css/index.css" rel="stylesheet" type="text/css"/>
    </head>
    <body>
        <div id="app">
            <!-- 商品列表 -->
            <h3>商品列表</h3>
            <ul id="goodsList">
              <template v-for="goods in goodsList" >
                <li class="goods-item" :key="goods.id">
                    <div><img :src="goods.imgUrl"/> </div> 
                    <div>{{goods.name}}</div> 
                    <div>¥ {{goods.price}} </div> 
                    <button @click="addToCart(goods)">加入购物车</button> 
                </li>
              </template>
            </ul>
            <!-- 购物车 -->
            <template v-if="cartList.length>0">
              <h3>购物车</h3>
              <ul id="cartList">
                <template v-for="goods in cartList">
                  <li class="goods-item" :key="goods.id">
                      <div><img :src="goods.imgUrl"/> </div> 
                      <div>{{goods.name}}</div> 
                      <div>¥ {{goods.price}} </div> 
                      <div class="item-control">
                          <button @click="removeGoods(goods)">-</button>
                          <h4>{{goods.num}}</h4>
                          <button @click="addToCart(goods)">+</button> 
                      </div>
                  </li>
                </template>
              </ul>
            </template>
        </div>
    </body>
</html>

<script>
    new Vue({
        el: '#app',
        data: {
          cartList:[],
          goodsList:[]
        },
        mounted() {
          this.goodsList = GoodsArr;
        },
        methods:{
            addToCart(goods){
                // TODO：修改当前函数，实现购物车加入商品需求
              let flag = true;
              this.cartList.forEach(item => {
              if (item.id == goods.id) {
              item.num += 1
              goods.num = item.num
              flag = !flag
            }
      })
              if (flag) {
              goods.num = 1;
              this.cartList.push(goods);
              this.cartList = JSON.parse(JSON.stringify(this.cartList));
            }
            },
            removeGoods(goods){
                // TODO：补全代码实现需求
                this.cartList.forEach((item,index) => {
                  if (item.id == goods.id && item.num > 0) {
                  item.num -= 1
                  goods.num = item.num
                  if (goods.num == 0) {
                  this.cartList.splice(index,1)
            }
          }
        })
            }
        }
    });
</script>